package com.ocm.tourism.web.validator;

import java.awt.Dimension;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ocm.tourism.core.exception.TourismRuntimeException;
import com.ocm.tourism.file.MimeTypeSupport;
import com.ocm.tourism.file.SimpleImageInfo;
import com.ocm.tourism.web.util.FileInfoUtil;

@Component
public class FileValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      return clazz.getName().equalsIgnoreCase(CommonsMultipartFile.class.getName());
   }

   @Override
   public void validate(Object target, Errors errors) {
      try {
         validate((CommonsMultipartFile) target, errors);
      } catch (IOException e) {
         throw new TourismRuntimeException(e.getMessage());
      }
   }

   public void validate(CommonsMultipartFile commonsMultipartFile, Errors errors) throws IOException{
      if (commonsMultipartFile.getSize() > 0){
         InputStream inputStream = commonsMultipartFile.getInputStream();
         if (!MimeTypeSupport.supportMineType(commonsMultipartFile.getContentType())){
            errors.reject("error_fileData_contenttype");
         }
         if (commonsMultipartFile.getSize() > FileInfoUtil.DEFAULT_BUFFER_SIZE){
            errors.reject("error_fileData_large");
         }
         if (!errors.hasFieldErrors("fileData")){
            Dimension dimension = SimpleImageInfo.processStream(inputStream);
            if (dimension.getWidth() < 200){
               errors.reject("error_fileData_limit_width");
            }
         }
      }
   }
   
}
